package com.shawn.server.interceptor;

import com.shawn.commons.utils.JwtUtils;
import com.shawn.model.entity.User;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {


    /**
     * 配置拦截器,验证请求token,判定是否合法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("Authorization");
/*        boolean res = JwtUtils.verifyToken(token);
        if (!res){
            response.setStatus(401);
            return false;
        }*/
        //解析token
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");
        String phone = (String) claims.get("phone");
        //存入线程变量副本
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(phone);
        ThreadContext.setUser(user);
        return true;
    }

    /**
     * 拦截完成后执行清空副本方法
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空副本
        ThreadContext.clear();
    }
}
